package com.tian.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.tian.common.CommonResult;
import com.tian.constant.RabbitMQConstant;
import com.tian.dto.SendCodeReqDto;
import com.tian.enums.MessageRetryType;
import com.tian.enums.MessageTypeEnum;
import com.tian.message.SendSMSMessage;
import com.tian.producer.MqProducer;
import com.tian.service.SendCodeService;
import com.tian.util.RedisConstantPre;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * {@code @description:} 发送·验证码·服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-08 19:14
 * {@code @version:} 1.0
 */
@Service
@Slf4j
public class SendCodeServiceImpl implements SendCodeService {
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private MqProducer mqProducer;

    @Override
    public CommonResult<String> sendCode(SendCodeReqDto sendCodeReqDto) {
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.getMessageTypeEnum(sendCodeReqDto.getType());
        if (messageTypeEnum == null) {
            return CommonResult.failed("短信类型错误");
        }
        String content = messageTypeEnum.getContent();
        String phone = sendCodeReqDto.getPhone();
        String code = RandomUtil.randomNumbers(6);
        content = content.replace("code", code);
        log.info("手机号：{}，发送验证码：{}", phone, content);
        RBucket<String> bucket = redissonClient.getBucket(RedisConstantPre.SEND_CODE_PRE + phone);
        bucket.set(code, 60, TimeUnit.SECONDS);
        SendSMSMessage sendSMSMessage=new SendSMSMessage();
        sendSMSMessage.setPhone(phone);
        sendSMSMessage.setContent(content);
        mqProducer.sendWithRetry(content, MessageRetryType.SMS.getType(), RabbitMQConstant.SMS_EXCHANGE, RabbitMQConstant.SMS_ROUTING_KEY);
        log.info("验证码发送成功");
        return CommonResult.success(code);
    }
}
